package ua.amsoft.brelok.task;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;
import android.util.Log;

public class CheckServerReachableTask extends AsyncTask<String, Void, Boolean> {
    
    private static final String RESPONSE_MESSAGE_OK = "OK";
    
    private static final String TAG = "CheckServerReachableTask";
    
    @Override
    protected Boolean doInBackground(final String... params) {
        boolean isServerReachable = false;
        try {
            isServerReachable = isServerReachable(params[0]);
        } catch (final IOException e) {
            Log.e(CheckServerReachableTask.TAG,
                    "Server isReachable checking failed: " + e.getLocalizedMessage());
        }
        return isServerReachable;
    }
    
    /**
     * Checks for is passed server is reachable
     * 
     * @param urlString - server's URL address
     * @return {@link Boolean} true or false
     * @throws IOException - exception to be throwed
     */
    private boolean isServerReachable(final String urlString) throws IOException {
        final URL url = new URL(urlString);
        final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        if (CheckServerReachableTask.RESPONSE_MESSAGE_OK.equalsIgnoreCase(urlConnection
                .getResponseMessage())) {
            Log.i(CheckServerReachableTask.TAG, url.getHost() + " Server is reachable");
            return true;
        }
        Log.i(CheckServerReachableTask.TAG, url.getHost() + " Server is unreachable");
        return false;
    }
    
}
